package com.jishucai.tomcat;

import com.jishucai.servlet.CustomServlet;
import io.netty.util.internal.StringUtil;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author qiaowang 2021/4/16
 */
public class Registry {
    // 加载并缓存指定包中所有的servletname数据
    private List<String> servletNameCache = new ArrayList<>();

    public void registServlet(String basePackage, Map<String, Object> registerMap) throws Exception {
        cacheServletClass(basePackage);
        if (servletNameCache.size() == 0) {
            return;
        }
        for (String className : servletNameCache) {
            Class<?> clazz = Class.forName(className);
            Type superclass = clazz.getGenericSuperclass();
            if (superclass == CustomServlet.class) {
                String simpleClassName = className.substring(className.lastIndexOf(".") + 1).toLowerCase();
                registerMap.put(simpleClassName, clazz.getDeclaredConstructor().newInstance());
            }

        }
    }

    private void cacheServletClass(String basePackage) {
        URL resource = this.getClass().getClassLoader().getResource(basePackage.replaceAll("\\.", "/"));
        if (resource == null) {
            return;
        }
        File dir = new File(resource.getFile());
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                cacheServletClass(basePackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                String filename = file.getName().replace(".class", "");
                servletNameCache.add(basePackage + "." + filename);
            }
        }

    }

}
